package cug.xxs.jpa.service;

import cug.xxs.jpa.domain.Fault;
import cug.xxs.jpa.domain.Layer;
import cug.xxs.jpa.domain.Model;
import cug.xxs.jpa.domain.Well;
import cug.xxs.jpa.repository.FaultRepo;
import cug.xxs.jpa.repository.LayerRepo;
import cug.xxs.jpa.repository.ModelRepo;
import cug.xxs.jpa.repository.WellRepo;
import cug.xxs.jpa.util.AbstractMyBeanUtils;
import cug.xxs.jpa.vo.FaultVo;
import cug.xxs.jpa.vo.LayerVo;
import cug.xxs.jpa.vo.ModelVo;
import cug.xxs.jpa.vo.WellVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: 彭诗杰
 * \* @date: 2019/7/27
 * \* @time: 16:17
 * \* Description:
 * \
 */
@Service("modelService")
public class ModelService implements IAction<Model, ModelVo, String> {

    @Resource(name = "modelRepo")
    private ModelRepo modelRepo;

    @Resource(name = "layerRepo")
    private LayerRepo layerRepo;

    @Resource(name = "faultRepo")
    private FaultRepo faultRepo;

    @Resource(name = "wellRepo")
    private WellRepo wellRepo;


    @Override
    public Model create(ModelVo modelVo) {

        Model model = new Model();
        AbstractMyBeanUtils.copyProperties(modelVo, model,
                "id", "layers", "faults", "wells");
        modelRepo.save(model);

        for (FaultVo faultVo : modelVo.getFaults()) {
            Fault fault = new Fault();
            AbstractMyBeanUtils.copyProperties(faultVo, fault);
            fault.setModel(model);
            faultRepo.save(fault);
        }

        for (WellVo wellVo : modelVo.getWells()) {
            Well well = new Well();
            AbstractMyBeanUtils.copyProperties(wellVo, well);
            well.setModel(model);
            wellRepo.save(well);
        }

        for (LayerVo layerVo : modelVo.getLayers()) {
            Layer layer = new Layer();
            AbstractMyBeanUtils.copyProperties(layerVo, layer);
            layer.setModel(model);
            layerRepo.save(layer);
        }
        return model;
    }

    @Override
    public Optional<Model> findById(String id) {
        return modelRepo.findById(id);
    }

    @Override
    public void deleteById(String id) throws EmptyResultException {
        if (!modelRepo.existsById(id)) {
            throw new EmptyResultException();
        }

        modelRepo.deleteById(id);
    }

    @Override
    public void update(ModelVo modelVo) {
        if (modelVo != null) {
            Optional<Model> modelOptional = modelRepo.findById(modelVo.getId());
            if (modelOptional.isPresent()) {
                AbstractMyBeanUtils.copyProperties(modelVo, modelOptional.get(),
                        "id", "layers", "faults", "wells");
                modelRepo.save(modelOptional.get());
            }
        }
    }
}
